package com.neusoft.controller;

import com.neusoft.feign.FoodFeignClient;
import com.neusoft.po.Business;
import com.neusoft.po.CommonResult;
import com.neusoft.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/BusinessController")
@RefreshScope
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @Qualifier("com.neusoft.feign.FoodFeignClient")
    @Autowired
    private FoodFeignClient foodFeignClient;

    @GetMapping("/listBusinessByOrderTypeId/{orderTypeId}")
    public CommonResult<List> listBusinessByOrderTypeId(
            @PathVariable("orderTypeId") Integer orderTypeId
    ) throws Exception {
        List<Business> list = businessService.listBusinessByOrderTypeId(orderTypeId);
        return new CommonResult(200, "success", list);
    }

    @GetMapping("/getBusinessById/{businessId}")
    public CommonResult<Business> getBusinessById(
            @PathVariable("businessId") Integer businessId
    ) throws Exception {
        Business business = businessService.getBusinessById(businessId);
        //在商家微服务中调用食品微服务
        CommonResult<List> result = foodFeignClient.listFoodByBusinessId(businessId);
        // 如果食品微服务返回降级相应,那么就返回空集合
        if (result.getCode() == 200) {
            business.setFoodList(result.getResult());
        }else{
            business.setFoodList(new ArrayList());
        }
        return new CommonResult(200, "success(10300)", business);
    }

	@RequestMapping("/listBusinessByOrderTypeId")
	public CommonResult<Integer> listBusinessByOrderTypeId(Business business) throws Exception {
		List<Business> i=businessService.listBusinessByOrderTypeId(business.getOrderTypeId())
		return new CommonResult(200, "success", i);
	}

	@RequestMapping("/getBusinessById")
	public CommonResult<Integer> getBusinessById(Business business) throws Exception {
		Business i=businessService.getBusinessById(Math.toIntExact(business.getBusinessId()));
		return new CommonResult(200, "success", i);
	}

	@RequestMapping("/getCurrentBusiness")
	public CommonResult<Integer> getCurrentBusiness(HttpSession session) {
		System.out.println("getCurrentBusiness method called");
		Long userIdLong = (Long) session.getAttribute("userId");
		String userId = userIdLong != null ? String.valueOf(userIdLong) : null;

		Business currentBusiness = businessService.getCurrentBusiness(userId);
		if (currentBusiness != null) {
			return ResponseEntity.ok(currentBusiness);
		} else {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("商家信息未找到");
		}
	}

}